<!-- 数据统计 - 广告效果统计 -->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="search-form"
      label-width="68px"
    >
      <el-form-item label="时间范围" prop="orderDate">
        <el-date-picker
          :clearable="false"
          v-model="queryParams.times"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          :shortcuts="defaultShortcuts"
          class="date-picker"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="广告账户" prop="accountId">
        <el-select
          v-model="queryParams.accountId"
          class="account-select"
          clearable
          placeholder="请选择广告账户"
          @change="handleQuery"
        >
          <el-option
            v-for="(user, index) in accountList"
            :key="index"
            :label="user.name"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="search-btn" @click="loadData">
          <Icon class="mr-5px" icon="ep:search" />
          查询
        </el-button>
        <el-button class="reset-btn" @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- Echarts图 -->
  <el-card shadow="never" class="chart-card">
    <el-tabs v-model="activeTab" class="custom-tabs">
      <!-- 按组件类型分析 -->
      <el-tab-pane label="按组件类型分析" name="type"> </el-tab-pane>
      <!-- 按广告账户分析 -->
      <el-tab-pane label="按广告账户分析" name="account"> </el-tab-pane>
      <!-- 按广告计划分析 -->
      <el-tab-pane label="按广告计划分析" name="plan"> </el-tab-pane>
    </el-tabs>
    <div class="chart-container">
      <div class="chart-wrapper">
        <Echart :height="chartHeight" :options="echartsOption" v-loading="loading" />
      </div>
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="list"
          border
          :max-height="tableHeight"
          class="data-table"
        >
          <el-table-column
            align="center"
            :label="
              activeTab == 'type' ? '组件类型' : activeTab == 'account' ? '广告账户' : '广告计划'
            "
            min-width="200"
            prop="name"
          />
          <el-table-column align="center" label="数量" min-width="200" prop="value" sortable />
        </el-table>
      </div>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { beginOfDay, defaultShortcuts, endOfDay, formatDate } from '@/utils/formatTime'
import * as AdEffectApi from '@/api/ad/statistics/effect'
import { getAccountSimpleList } from '@/api/ad/account/index'

defineOptions({ name: 'CrmStatisticsTag' })

const queryFormRef = ref() // 搜索的表单
const queryParams = reactive({
  accountId: undefined,
  times: [
    // 默认显示最近一周的数据
    formatDate(beginOfDay(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7))),
    formatDate(endOfDay(new Date(new Date().getTime() - 3600 * 1000 * 24)))
  ]
})
const loading = ref(false) // 加载中
const list = ref([]) // 列表的数据

// 响应式高度
const chartHeight = ref(500)
const tableHeight = ref(500)

// 检测屏幕尺寸
const checkScreenSize = () => {
  const width = window.innerWidth
  if (width <= 768) {
    chartHeight.value = 300
    tableHeight.value = 300
  } else {
    chartHeight.value = 500
    tableHeight.value = 500
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.accountId = undefined
  queryParams.times = [
    formatDate(beginOfDay(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7))),
    formatDate(endOfDay(new Date(new Date().getTime() - 3600 * 1000 * 24)))
  ]
  loadData()
}
const activeTab = ref('type')
const title = ref('按组件类型分析')
// 当 activeTab 改变时，刷新当前活动的 tab
watch(activeTab, (newTab) => {
  if (newTab == 'type') {
    title.value = '按组件类型分析'
  }
  if (newTab == 'account') {
    title.value = '按广告账户分析'
  }
  if (newTab == 'plan') {
    title.value = '按广告计划分析'
  }
  loadData()
})

/** 饼图配置（全部客户） */
const echartsOption = reactive<EChartsOption>({
  title: {
    text: title,
    left: 'center',
    textStyle: {
      color: '#0052cc',
      fontSize: 16,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'item',
    backgroundColor: 'rgba(0, 82, 204, 0.9)',
    borderColor: '#0052cc',
    textStyle: {
      color: '#fff'
    }
  },
  legend: {
    type: 'scroll',
    bottom: 0,
    icon: 'circle',
    itemHeight: 6, // 修改icon图形大小
    itemGap: 12, // 修改间距
    textStyle: {
      fontSize: 12,
      color: '#333',
      padding: [0, 0, 0, -8] // 修改文字和图标距离
    }
  },
  toolbox: {
    feature: {
      saveAsImage: { show: true, name: title } // 保存为图片
    },
    iconStyle: {
      borderColor: '#0052cc'
    }
  },
  series: [
    {
      name: title,
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold',
          color: '#0052cc'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
}) as EChartsOption
/** 获取统计数据 */
const loadData = async () => {
  // 1. 加载统计数据
  loading.value = true
  let industryList = null
  if (activeTab.value == 'type') {
    industryList = await AdEffectApi.getSummaryByClueType(queryParams)
  }

  if (activeTab.value == 'account') {
    industryList = await AdEffectApi.getSummaryByAdvertiser(queryParams)
  }

  if (activeTab.value == 'plan') {
    industryList = await AdEffectApi.getSummaryByPromotion(queryParams)
  }
  const resData = ref([])
  // 2.1 更新 Echarts 数据
  if (echartsOption.series && echartsOption.series[0] && echartsOption.series[0]['data']) {
    resData.value = industryList.map((r) => {
      return {
        name: r.name ? r.name : '其他',
        value: r.value
      }
    })
    echartsOption.series[0]['data'] = resData.value
  }

  list.value = resData.value
  loading.value = false
}
const accountList = ref([])
/** 初始化 */
onMounted(async () => {
  accountList.value = await getAccountSimpleList()
  await loadData()
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize)
})
</script>

<style scoped>
/* 搜索表单样式 */
.search-form {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
}

.date-picker {
  width: 240px;
}

.account-select {
  width: 240px;
}

.search-btn {
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 82, 204, 0.4);
}

.reset-btn {
  border: 2px solid #0052cc;
  color: #0052cc;
  border-radius: 8px;
  padding: 8px 18px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-left: 10px;
}

.reset-btn:hover {
  background: #0052cc;
  color: white;
  transform: translateY(-2px);
}

/* 卡片样式 */
.chart-card {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 82, 204, 0.1);
  border: 1px solid rgba(0, 82, 204, 0.1);
  overflow: hidden;
}

/* 标签页样式 */
.custom-tabs {
  margin-bottom: 20px;
}

.custom-tabs :deep(.el-tabs__header) {
  margin: 0 0 20px 0;
  border-bottom: 2px solid #f0f2f5;
}

.custom-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.custom-tabs :deep(.el-tabs__item) {
  color: #666;
  font-weight: 500;
  padding: 0 20px;
  height: 44px;
  line-height: 44px;
  border-radius: 8px 8px 0 0;
  margin-right: 4px;
  transition: all 0.3s ease;
}

.custom-tabs :deep(.el-tabs__item:hover) {
  color: #0052cc;
  background: rgba(0, 82, 204, 0.05);
}

.custom-tabs :deep(.el-tabs__item.is-active) {
  color: #0052cc;
  background: linear-gradient(135deg, rgba(0, 82, 204, 0.1) 0%, rgba(0, 102, 255, 0.1) 100%);
  border-bottom: 3px solid #0052cc;
  font-weight: 600;
}

.custom-tabs :deep(.el-tabs__active-bar) {
  background: #0052cc;
  height: 3px;
}

/* 图表容器样式 */
.chart-container {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.chart-wrapper {
  flex: 1;
  min-width: 300px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.08);
}

.table-wrapper {
  flex: 1;
  min-width: 300px;
}

/* 表格样式 */
.data-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.08);
}

.data-table :deep(.el-table__header) {
  background: linear-gradient(135deg, #0052cc 0%, #0066ff 100%);
}

.data-table :deep(.el-table__header th) {
  background: transparent;
  color: white;
  font-weight: 600;
  border: none;
  padding: 16px 12px;
}

.data-table :deep(.el-table__body tr:hover > td) {
  background: rgba(0, 82, 204, 0.05) !important;
}

.data-table :deep(.el-table__body td) {
  border-bottom: 1px solid #f0f2f5;
  padding: 14px 12px;
}

.data-table :deep(.el-table__body tr:nth-child(even)) {
  background: #fafbfc;
}

/* H5响应式样式 */
@media (max-width: 768px) {
  .search-form {
    padding: 15px;
  }

  .search-form :deep(.el-form-item) {
    margin-bottom: 15px;
    width: 100%;
  }

  .search-form :deep(.el-form-item__label) {
    width: 80px !important;
    font-size: 14px;
  }

  .date-picker,
  .account-select {
    width: 100% !important;
    max-width: 280px;
  }

  .search-btn,
  .reset-btn {
    width: 100%;
    margin: 5px 0;
  }

  .chart-container {
    flex-direction: column;
    gap: 15px;
  }

  .chart-wrapper {
    min-width: auto;
    padding: 15px;
  }

  .table-wrapper {
    min-width: auto;
  }

  .custom-tabs :deep(.el-tabs__item) {
    padding: 0 12px;
    font-size: 14px;
  }

  .data-table :deep(.el-table__header th),
  .data-table :deep(.el-table__body td) {
    padding: 12px 8px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .search-form {
    padding: 12px;
  }

  .chart-wrapper {
    padding: 12px;
  }

  .custom-tabs :deep(.el-tabs__item) {
    padding: 0 8px;
    font-size: 13px;
  }

  .data-table :deep(.el-table__header th),
  .data-table :deep(.el-table__body td) {
    padding: 10px 6px;
    font-size: 13px;
  }
}
</style>
